package util

import (
	"crypto/md5"
	"crypto/rc4"
	"encoding/base64"
	"fmt"
	"log"
	"WDserver/config"
	"os"
	"strings"
)


//加密数据
func EncodeString(contnet string) []byte {
	c, err := rc4.NewCipher([]byte(config.Config().Rc4Key))
	if err != nil {
		log.Fatalln(err)
	}
	src := []byte(contnet)
	dst := make([]byte, len(src))
	c.XORKeyStream(dst, src)

	str := base64.StdEncoding.EncodeToString(dst)
	return []byte(str)
}

//解密数据
func EecodeBytes(contnet []byte) string {
	str, err := base64.StdEncoding.DecodeString(string(contnet))
	if err != nil {
		log.Fatalln(err)
	}
	c, err := rc4.NewCipher([]byte(config.Config().Rc4Key))
	if err != nil {
		log.Fatalln(err)
	}
	src := []byte(str)
	dst := make([]byte, len(src))
	c.XORKeyStream(dst, src)
	return string(dst)
}

func Md5Passwd(user, password string) string {
	pass := MD5sum(password)
	passwd := MD5sum(user + pass + "20070201")
	return passwd
}

func Checksum(user string, password string, privilege int, jyb int, yyb int) string {
	data := fmt.Sprintf("%s%s%08X%s%08X%08X%s%s%s%s%sABCDEF", user, password, privilege, "", jyb, yyb, "", "", "", "", "")
	data1 := md5.Sum([]byte(data))
	str := strings.ToUpper(fmt.Sprintf("%8X", data1))
	return str
}

func MD5sum(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	md5str1 := fmt.Sprintf("%08X", has)
	return strings.ToUpper(md5str1)

}


//日志处理
func Log(v ...interface{}) {
	log.Println(v...)
}

//错误处理
func CheckError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())

	}
}